/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.contract.db.impl;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.yunhoo.contract.model.ConExecDetail;
import com.yunhoo.contract.model.ConExecMaster;
import com.yunhoo.contract.util.DocumentQueryConditionBeanExecute;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.ToolKit;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConExecImpl {

    private static final String NAMESPACE_MASTER = "Conexec.";

    public static String getMaxNumber() {
        Integer max = (Integer) IbatisTemplate.query(NAMESPACE_MASTER + "maxConexecVnumber", paramMap());
        if (max == null) max = 0;
        return String.format("%06d%n", max + 1).trim();
    }

    public static String buildNumber(SqlMapClient client) throws SQLException {
        Integer max = (Integer) client.queryForObject(NAMESPACE_MASTER + "maxConexecVnumber", paramMap());
        if (max == null) max = 0;
        return String.format("%06d%n", max + 1).trim();
    }

    private static Map paramMap() {
        Map map = new HashMap();
        map.put("orgCode", LoginParam.getOrg().getCode());
        return map;
    }

    public static boolean save(ConExecMaster master, List<ConExecDetail> details, boolean addOrUpdate) {

        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            //client.startBatch();
            if (addOrUpdate) {
                /* 设置编号 */
                String maxNumber = buildNumber(client);
                master.setVounumber(maxNumber);

                /* 保存Master*/
                client.insert(NAMESPACE_MASTER + "insertMaster", master);
            } else {
                //修改
                client.update(NAMESPACE_MASTER + "updateMaster", master);
            }


            /* 注意，这里的删除 必须在 下面的 验证之前，否则 修改时 下面的验证 无法使用 */
            Map map = paramMap();
            map.put("vounumber", master.getVounumber());
            client.delete(NAMESPACE_MASTER + "delectDetail", map);

            /* 获取 当前 每个contentId 对应的 可执行数量 （用合同内容中的数量 减 已执行数量合计）*/
            Map<Integer, Double> remainCountMap = remainCount(client);

            /* 验证：任一条目的 执行数量 超出 对应的 可执行数量，则保存中止 */
            for (ConExecDetail d : details) {
                Double remainCount = remainCountMap.get(d.getContentId());
                if (d.getCount() > remainCount) {
                    ToolKit.msgs_err("执行数量，不能超出合同内容中剩余数量");
                    return false;
                }
            }

            for (ConExecDetail d : details) {
                d.setVounumber(master.getVounumber());
                client.insert(NAMESPACE_MASTER + "insertDetail", d);
            }

            //client.executeBatch();
            client.commitTransaction();
        } catch (SQLException ex) {
            Logger.getLogger(ContractImpl.class.getName()).log(Level.SEVERE, null, ex);

            /* 遇到异常，返回false,注意：返回之前 finally 内的内容会执行，故不用担心会跳过finally */
            return false;
        } finally {
            try {
                client.endTransaction();
            } catch (SQLException ex) {
                Logger.getLogger(ContractImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(" * * * " + " finlly " + "  * * * ");
        }

        /* 程序正常结束，返回true */
        return true;
    }

    public static boolean save_(ConExecMaster master, List<ConExecDetail> details, boolean addOrUpdate) {

        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            client.startBatch();

            if (addOrUpdate) {
                insert(client, master, details);
            } else {
                update(client, master, details);
            }

            client.executeBatch();
            client.commitTransaction();

        } catch (SQLException ex) {
            Logger.getLogger(ContractImpl.class.getName()).log(Level.SEVERE, null, ex);

            /* 遇到异常，返回false,注意：返回之前 finally 内的内容会执行，故不用担心会跳过finally */
            return false;
        } finally {
            try {
                client.endTransaction();
            } catch (SQLException ex) {
                Logger.getLogger(ContractImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(" * * * " + " finlly " + "  * * * ");
        }

        /* 程序正常结束，返回true */
        return true;
    }

    private static void insert(SqlMapClient client, ConExecMaster master, List<ConExecDetail> details) throws SQLException {
        /* 设置编号 */
        String maxNumber = buildNumber(client);
        master.setVounumber(maxNumber);

        /* 保存Master*/
        client.insert(NAMESPACE_MASTER + "insertMaster", master);

        Map map = paramMap();
        map.put("vounumber", master.getVounumber());
        client.delete(NAMESPACE_MASTER + "delectDetail", map);

        Map<Integer, Double> remainCountMap = remainCount(client);

        for (ConExecDetail d : details) {
            Double remainCount = remainCountMap.get(d.getContentId());
            if (d.getCount() > remainCount) {
                return;
            }
        }

        for (ConExecDetail d : details) {
            Double remainCount = remainCountMap.get(d.getContentId());
            if (d.getCount() > remainCount) {
                d.setVounumber(master.getVounumber());
                client.insert(NAMESPACE_MASTER + "insertDetail", d);
            }
        }
    }

    private static Map<Integer, Double> remainCount(SqlMapClient client) throws SQLException {
        String orgCode = LoginParam.getOrg().getCode();
        return client.queryForMap(NAMESPACE_MASTER + "queryContentRemainCount", orgCode, "id", "countRemain");
    }

    private static void update(SqlMapClient client, ConExecMaster master, List<ConExecDetail> details) throws SQLException {
        //修改
        client.update(NAMESPACE_MASTER + "updateMaster", master);

        Map map = paramMap();
        map.put("vounumber", master.getVounumber());
        client.delete(NAMESPACE_MASTER + "delectDetail", map);

        for (ConExecDetail d : details) {
            d.setVounumber(master.getVounumber());
            client.insert(NAMESPACE_MASTER + "insertDetail", d);
        }
    }

    public static void insertMaster(ConExecMaster con) {
        IbatisTemplate.insert(NAMESPACE_MASTER + "insertMaster", con);
    }

    public static void insertDetail(ConExecDetail con) {
        IbatisTemplate.insert(NAMESPACE_MASTER + "insertDetail", con);
    }

    public static List<ConExecDetail> queryDetail() {
        return IbatisTemplate.queryForList(NAMESPACE_MASTER + "selectDetail", paramMap());
    }

    public static List<ConExecMaster> queryExecStats(String number) {
        Map map = paramMap();
        map.put("number", number);
        return IbatisTemplate.queryForList(NAMESPACE_MASTER + "queryExecStats", map);
    }

    public static List<ConExecMaster> queryMaster() {
        return IbatisTemplate.queryForList(NAMESPACE_MASTER + "selectMaster", paramMap());
    }

    public static List<ConExecDetail> queryDetailByNumber(String vounumber) {
        Map map = paramMap();
        map.put("vounumber", vounumber);
        return IbatisTemplate.queryForList(NAMESPACE_MASTER + "queryExecDetailByNumber", map);
    }

    public static List<ConExecDetail> queryDetailByContractNumber(String number) {
        Map map = paramMap();
        map.put("number", number);
        return IbatisTemplate.queryForList(NAMESPACE_MASTER + "queryDetailByContractNumber", map);
    }

    public static void deleteDetail(String vounumber) {
        Map map = paramMap();
        map.put("vounumber", vounumber);
        IbatisTemplate.delete(NAMESPACE_MASTER + "delectDetail", map);
    }

    public static void updateMaster(ConExecMaster master) {
        IbatisTemplate.update(NAMESPACE_MASTER + "updateMaster", master);
    }

    public static void deleteMaster(String vounumber) {
        Map map = paramMap();
        map.put("vounumber", vounumber);
        IbatisTemplate.delete(NAMESPACE_MASTER + "deleteMaster", map);
    }

//    public static List<Contract> queryContract() throws SQLException {
//        List<Contract> lt = null;
//         SqlMapClient sqlMap = IbatisTemplate.getSqlMapClient();
//        sqlMap.startTransaction();
//        lt = sqlMap.queryForList("selectContract");
//        sqlMap.commitTransaction();
//        return lt;
//    }
//      public static List<ConInfo> queryContract() throws SQLException {
//        List<ConInfo> lt = null;
//         SqlMapClient sqlMap = IbatisTemplate.getSqlMapClient();
//        sqlMap.startTransaction();
//        lt = sqlMap.queryForList("selectContract");
//        sqlMap.commitTransaction();
//        return lt;
//    }
    public static List<ConExecMaster> queryExecuteMaster(DocumentQueryConditionBeanExecute cem) {
        Map params = new HashMap();
        params.put("orgCode", LoginParam.getOrg().getCode());
        params.put("iyear", LoginParam.getIyear());
        if (cem != null) {
            params.put("vounumber", cem.getVounumber());
            params.put("contype", cem.getContype());
            params.put("number", cem.getNumber());
            params.put("voudateStart", cem.getVoudateStart());
            params.put("voudateEnd", cem.getVoudateEnd());
            params.put("name_detail", cem.getName_detail());
            params.put("tech_detail", cem.getTech_detail());
            params.put("countStart_detail", cem.getCountStart_detail());
            params.put("countEnd_detail", cem.getCountEnd_detail());
            params.put("priceStart_detail", cem.getPriceStart_detail());
            params.put("priceEnd_detail", cem.getPriceEnd_detail());
            params.put("totalStart_detail", cem.getTotalStart_detail());
            params.put("totalEnd_detail", cem.getTotalEnd_detail());
        }
        return IbatisTemplate.queryForList(NAMESPACE_MASTER + "queryExecuteMaster", params);
    }

    public static void main(String[] args) throws SQLException {
//        try {
//            DocumentQueryConditionBeanExecute dc = new DocumentQueryConditionBeanExecute();
//            dc.setVounumber("1");
//            Date ec = new Date();
//            ec.setMonth(6);
//            ec.setDate(1);
//            Date end = new Date();
//            end.setMonth(6);
//            end.setDate(30);
//            dc.setVoudateStart(ec);
//            dc.setVoudateEnd(end);
//            System.out.println("Date:" + ec);
//            List<ConExecMaster> li = queryExecuteMaster(dc);
//            for (ConExecMaster l : li) {
//                System.out.println(l.getContype());
//                System.out.println(l.getNumber());
//                System.out.println(l.getVounumber());
//                System.out.println(l.getVoudate());
//            }
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        client.startTransaction();
        Map<Integer, Double> rcMap = remainCount(client);
        client.commitTransaction();
        System.out.println(" * * * " + rcMap + "  * * * ");

    }
}
